const regeneratorRuntime = require("../../utils/runtime.js")
const login = require('../../utils/utils.js')
const {
  _post,
  _get
} = require('../../utils/request.js')
const App = getApp()
Page({
  data: {
    sideBarShow: {
      show: false
    },
    labels: [],
    nextRefresh: false,
    isFirstLoad: true,
    //loginShow: false,
    articleList: [],
    currentTab: 0,
    refreshing: false,
    page: 1,
    limit: 10,
    hasNextPage: false,
    label: '前端',

    touchStart: 0,
    touchEnd: 0,

    pulling: true,

    actionId: 0,
    actionShow: false,
    actions: [{
        name: '分享给朋友',
        openType: 'share'
      },
      {
        name: '复制链接'
      }
    ]
  },

  async onLoad() {
    setTimeout(() => {
      this.setData({
        pulling: true
      })
    }, 100)
    await this.getArticleList()
    await this.getLabels()
  },

  // async checkLogin() {
  //   try {
  //     let res = await login.login()
  //     App.state.isLogin = true
  //     this.setData({
  //       loginShow: false
  //     })
  //   } catch (err) {
  //     App.state.isLogin = false
  //     this.setData({
  //       loginShow: true
  //     })
  //   }
  // },

  // async gotUserInfo(info) {
  //   console.log(info)
  //   await this.checkLogin()
  //   let res = await _post('/wx', {
  //     code: wx.getStorageSync('loginCode').code,
  //     raw_data: JSON.stringify(wx.getStorageSync('userInfo'))
  //   })

  //   if (res.code === 0) {
  //     wx.setStorageSync('auth', res.data)
  //   }
  // },

  async getArticleList(isReload) {
    if (this.data.refreshing) {
      return
    }
    this.setData({
      refreshing: true,
      pulling: true
    })
    let lastInfo = []
    if (!this.data.isFirstLoad) {
      wx.showNavigationBarLoading()
    }
    if (isReload) {
      lastInfo = this.data.articleList.list
    } else {
      this.setData({
        page: 1,
      })
    }
    let res = await _get('/article', {
      page: this.data.page,
      limit: this.data.limit,
      label: this.data.label
    })
    if (res.code === 0) {
      let articleList = res.data
      let hasNextPage = this.data.page < articleList.total_page
      if (lastInfo.length > 0 && articleList.list && articleList.list instanceof Array && articleList.list.page > 1) {
        articleList.list = lastInfo.concat(articleList.list)
      }
      this.setData({
        articleList,
        hasNextPage
      })
    }
    wx.hideNavigationBarLoading()

    if (this.data.isFirstLoad) {
      this.setData({
        isFirstLoad: false
      })
    }

    this.setData({
      refreshing: false,
      pulling: false
    })
  },

  handleTabChange(e) {
    if (e.detail.index >= 0) {
      let lable = this.data.articleList.label[e.detail.index]
      if (lable.name !== this.data.label) {
        this.setData({
          label: lable.name,
          currentTab: e.detail.index
        })
        this.getArticleList(true)
      }
    }
  },

  async handleLoadNextPage() {
    if (this.data.hasNextPage) {
      this.setData({
        page: this.data.page + 1
      })
      await this.getArticleList(true)
    }
  },

  handleGetShareInfo({
    detail
  }) {
    this.setData({
      actionId: detail.id,
      actionShow: true
    })
  },

  handleActionClose() {
    this.setData({
      actionShow: false,
      actionId: 0
    })
  },

  handleActionSelect({
    detail
  }) {
    if (detail.name === '复制链接') {
      wx.setClipboardData({
        data: `https://aside.fun/archives/${this.data.actionId}`,
        success() {
          wx.showToast({
            title: '内容已复制',
            icon: 'none'
          })
        }
      })
    }
  },

  onShareAppMessage() {
    let shareInfo = {
      title: '别摸鱼了，起来刷题',
      imageUrl: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1579524369513&di=495f486dd0f5a9ac99fe090b49ac68f4&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201803%2F03%2F20180303170608_nJAx8.jpeg',
      path: this.data.actionId ? 'pages/article/article?id=' + this.data.actionId : 'pages/index/index',
      success() {
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log('转发成功')　　　　　　
        }
      },
      fail() {　　　
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          console.log('取消转发')
        } else if (res.errMsg == 'shareAppMessage:fail') {　
          console.log('转发失败')
        }
      },
    }

    return shareInfo
  },

  async getLabels() {
    let res = await _get('/label')
    if (res.code === 0) {
      this.setData({
        labels: res.data
      })
    }
  },

  handleShowSideBar() {
    this.setData({
      sideBarShow: {
        show: true
      }
    })
  },

  async handlePulling(e) {
    if (e.detail.scrollTop <= -80 && !this.data.refreshing) {
      this.setData({
        nextRefresh: true
      })
    }
  },

  handleTouchStart(e) {
    this.setData({
      touchStart: e.touches[0]['clientX']
    })
  },

  async handleTouchEnd(e) {
    this.setData({
      touchEnd: e.changedTouches[0]['clientX']
    })

    if (this.data.nextRefresh && !this.data.refreshing) {
      this.setData({
        nextRefresh: false
      })
      await this.getArticleList()
    }

    if (!this.data.articleList.label || !this.data.articleList.label.length) return

    if (this.data.touchStart - this.data.touchEnd >= 50) {
      if (this.data.currentTab + 1 < this.data.articleList.label.length) {
        this.setData({
          currentTab: this.data.currentTab + 1
        })
        await this.handleTabChange({
          detail: {
            index: this.data.currentTab
          }
        })
      } else if (this.data.currentTab + 1 === this.data.articleList.label.length) {
        this.setData({
          currentTab: 0
        })
        await this.handleTabChange({
          detail: {
            index: this.data.currentTab
          }
        })
      }
    }
    if (this.data.touchEnd - this.data.touchStart >= 50) {
      if (this.data.currentTab - 1 >= 0) {
        this.setData({
          currentTab: this.data.currentTab - 1
        })
        await this.handleTabChange({
          detail: {
            index: this.data.currentTab
          }
        })
      } else {
        this.handleShowSideBar()
      }
    }
    this.setData({
      touchStart: 0,
      touchEnd: 0
    })
  }

})